package cn.ac.cintcm.synonymous;

import java.util.Arrays;
import java.util.HashMap;

public class ResultTerms implements PagedData {
    
    protected HashMap<String, Term> terms;
    String[][] data;
    private boolean sort = true;
    
    public ResultTerms() {
        terms = new HashMap<String, Term>();
    }
    
    public void addTerms(Term t) {
        if (t != null) {
            if (terms.containsKey(t.getName())) {
                terms.get(t.getName()).addSource(t.getSource());
            } else {
                terms.put(t.getName(), t);
            }
        }
        
    }
    
    public Term getTerm(String name) {
        return terms.get(name);
    }
    
    public void removeTerm(String term) {
        terms.remove(term);
        toArray();
    }

    public String[][] getData() {
        if (data == null) {
            toArray();
        }
        return data;
    }


    private void toArray() {
        data = new String[terms.size() + 1][Term.ATTRIBUTE_SIZE];
        int i = 0;
        Term[]  termsArray = null;
        if(sort ) {
            termsArray = terms.values().toArray(new Term[0]);
            Arrays.sort(termsArray);
        }
        for (Term t : termsArray) {
            data[++i] = t.toArray();
        }
    }

    public int getLength() {
        if (data == null) {
            toArray();
        }
        return data.length - 1;
    }

    public void empty() {
        terms.clear();
        data = null;
        
    }

    public boolean isSort() {
        return sort;
    }

    public void setSort(boolean sort) {
        this.sort = sort;
    }
    

}
